package com.nice.email;

import com.alibaba.fastjson.JSON;
import com.nice.BeanUtil;
import com.nice.Commons;
import com.nice.cache.CacheMap;
import com.nice.email.dto.vo.MailSendVo;
import com.nice.email.util.MailUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class SendEmailThread implements Runnable{
    private final static Logger logger = LoggerFactory.getLogger(SendEmailThread.class);

    @Autowired
    private MailUtil mailUtil;

    //这里加Autowired不知道为什么取不到，fuck
    //所以写了一个BeanUtils获取bean
    private CacheMap cacheMap;

    private boolean active = true;

    private boolean isUse= true;

    private Long interval= Commons.CACHE_OVERTIME;

    /**
     * 构造类启动线程
     */
    public SendEmailThread(){
        init();
    }

    /**
     * 启动线程
     */
    public  void init() {
        mailUtil= (MailUtil) BeanUtil.getBean("mailUtil");
        cacheMap= (CacheMap) BeanUtil.getBean("cacheMap");

        if(isUse) {
            logger.info("邮件线程启动,间隔{}秒",interval);
            this.active=true;
            try {
                Thread.sleep(1000L*5);
            } catch (Exception e) {

            }
            new Thread(this).start();
        }else {
            logger.info("牌价刷新线程未启动");
        }
    }

    @Override
    public void run() {
        while(active) {
            try {
                getSendEmailUser();
                Thread.sleep(1000L*interval);
            } catch (Exception e) {
                logger.error("邮件线程异常{}",e);
            }
        }
    }

    //发送邮件
    public void getSendEmailUser(){
        //待发送的邮件列表
        Map<String,String> map =this.cacheMap.getEmailMap();
        List<String> list = new ArrayList<String>();
        if (map != null) {
            for (String key : map.keySet()) {
                list.add(key);
            }
        }else{
            logger.info("暂时没有邮件需要发送");
        }

        for (int i = 0; i < list.size(); i++) {
            String key = list.get(i);
            String[] strArray = key.split(":");
            String email = strArray[0];
            String priceName = strArray[1];
            String content = map.get(key);
            try {
                //发送邮件
                sendEmail(email, content,priceName);
            } catch (Exception e) {
                logger.error("邮件发送异常{}",e);
            }finally {
                //不管发送成功还是失败。都从邮件列表删除
                map.remove(key);
            }
        }
    }

    public void sendEmail(String email,String content,String priceName) throws Exception {
        MailSendVo mailSendVo = new MailSendVo();
        mailSendVo.setToMail(email);
        mailSendVo.setTitle(priceName+"到价邮件");
        mailSendVo.setContent(content);
        boolean result = mailUtil.send(mailSendVo);
        if (result) {
            logger.info("到价邮件发送成功:{}" , JSON.toJSONString(mailSendVo));
        }else{
            logger.info("到价邮件发送失败:{}" , JSON.toJSONString(mailSendVo));

        }
    }

}
